package satir.framework.test;

import java.lang.reflect.Field;
import junit.framework.Assert;

/**
 * Provides access to private members in classes.
 * @version 3.0 April 2012
 * @author Creative Family
 */
public final class PrivateAccessor {

    /**
     * Instantiates a new private accessor.
     */
    private PrivateAccessor() {
    }
    /**
     * Gets the private field.
     * @param o
     *            the object
     * @param fieldName
     *            the field name
     * @return the private field
     */
    public static Object getPrivateField(final Object o, final String fieldName) {
	/* Check we have valid arguments */
	Assert.assertNotNull(o);
	Assert.assertNotNull(fieldName);
	/* Go and find the private field... */
	final Field[] fields = o.getClass().getDeclaredFields();
	for (int i = 0; i < fields.length; ++i) {
	    if (fieldName.equals(fields[i].getName())) {
		try {
		    fields[i].setAccessible(true);
		    return fields[i].get(o);
		} catch (IllegalAccessException ex) {
		    Assert.fail("IllegalAccessException accessing "
			    + fieldName
			    + ", please contact Tsui To, Chris Chan or Ivan Chung");
		}
	    }
	}
	Assert.fail("Field '"
		+ fieldName
		+ "' not found, please contact Tsui To, Chris Chan or Ivan Chung");
	return null;
    }
}
